package com.itheima.stock.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.itheima.stock.entity.StockBlockRtInfo;
import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockRtInfo;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.properties.MarketProperties;
import com.itheima.stock.service.StockTimerService;
import com.itheima.stock.util.DateTimeUtil;
import com.itheima.stock.util.IdWorkers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zxh
 * @created 2024/12/18 19:35
 * @description
 */
@Service
@Slf4j
public class StockTimerServiceImpl implements StockTimerService {
    @Autowired
    private IdWorkers idWorker;
    @Autowired
    private StockMarketIndexInfoMapper marketIndexInfoMapper;
    @Autowired
    private MarketProperties marketProperties;

    private final RestTemplate restTemplate;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    public StockTimerServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void getStockBlockInfo() {
        String url = "http://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php";
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<HttpHeaders> entity = new HttpEntity<>(headers);
        //发起请求
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String body = response.getBody();
        String reg= "var S_Finance_bankuai_sinaindustry = (.+)";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(body);

        List<StockBlockRtInfo> stockBlockRtInfoList = new ArrayList<>();
        while (matcher.find()) {
            String json = matcher.group(1);
            Map map = JSON.parseObject(json, Map.class);
            Collection values = map.values();
            for (Object valueStr : values) {
                String value = valueStr.toString();
                String[] split = value.split(",");
                String label = split[0];
                String block_name = split[1];
                Integer company_num = Integer.parseInt(split[2]);
                BigDecimal avg_price = new BigDecimal(split[3]);
                BigDecimal updown_rate = new BigDecimal(split[5]);
                Long trade_amount = Long.parseLong(split[6]);
                BigDecimal trade_volume = new BigDecimal(split[7]);
                StockBlockRtInfo blockRtInfo = StockBlockRtInfo.builder()

                        .id(idWorker.nextStrId())
                        .label(label)
                        .blockName(block_name)
                        .companyNum(company_num)
                        .avgPrice(avg_price)
                        .updownRate(updown_rate)
                        .tradeAmount(trade_amount)
                        .tradeVolume(trade_volume)
                        .curTime(LocalDateTime.now())
                        .build();
                stockBlockRtInfoList.add(blockRtInfo);

            }
        }
        stockBlockRtInfoMapper.insertBatch(stockBlockRtInfoList);

    }

    @Override
    public void getStockInfo(String bizId) {
        String urlPrefix = "https://hq.sinajs.cn/list";
        //拼接URL参数
        List<StockBusiness> stockBusinesses = stockBusinessMapper.selectAll();
        List<String> list = stockBusinesses.stream().map((business)->{
            if ( business.getSectorCode().startsWith("00")){
                return String.join("","sz", business.getSectorCode());
            } else if ( business.getSectorCode().startsWith("60")) {
                return String.join("","sh", business.getSectorCode());

            }else{
                return null;
            }

        }).toList();
        String param  = String.join(",",list);
        String url = String.join("=", urlPrefix, param);
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<HttpHeaders> entity = new HttpEntity<>(headers);
        //发起请求
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String body  = response.getBody();
        String reg="var hq_str_[a-z][a-z](\\d.+)=\"(.+)\";";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(body);

        List<StockRtInfo> stockRtInfoList = new ArrayList<>();
        while (matcher.find()) {
            //获取股票的id
            String stockCode = matcher.group(1);
            //其它信息
            String other = matcher.group(2);
            String[] others = other.split(",");
            //股票名称
            String stockName=others[0];
            BigDecimal openPrice=new BigDecimal(others[1]);
            //当前价格
            BigDecimal curPrice=new BigDecimal(others[3]);

            BigDecimal preClosePrice =new BigDecimal(others[2]);
            BigDecimal maxPrice =new BigDecimal(others[4]);
            BigDecimal minPrice =new BigDecimal(others[5]);
            Long tradeAmount =Long.parseLong(others[8]);
            BigDecimal tradeVolume =new BigDecimal(others[9]);
            String date_str = others[30];
            String time_str = others[31];
            String date_time_str = String.join("-",date_str,time_str);
            LocalDateTime dateTime = LocalDateTime.parse(date_time_str, DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss"));


            StockRtInfo stockRtInfo = StockRtInfo.builder()
                    .id(idWorker.nextStrId())
                    .stockCode(stockCode)
                    .curTime(dateTime)
                    .stockName(stockName)
                    .openPrice(openPrice)
                    .preClosePrice(preClosePrice)
                    .curPrice(curPrice)
                    .maxPrice(maxPrice)
                    .minPrice(minPrice)
                    .tradeAmount(tradeAmount)
                    .tradeVolume(tradeVolume)
                    .build();
            stockRtInfoList.add(stockRtInfo);
        }
        //将结果插入数据库（分片）
        Lists.partition(stockRtInfoList, 10).stream().forEach(list1->{
            stockRtInfoMapper.insertBatch(list1);
        });
    }

    @Override
    public void getInnerMarketInfo() {
        //组装动态url
        //http://hq.sinajs.cn/list=s_sh000001,s_sz399001
        String innerUrl="https://hq.sinajs.cn/list=";
//        String innerUrl=stockInfoConfig.getMarketUrl()+String.join(",",stockInfoConfig.getInner());
        List<String> ids = marketProperties.getInner();
        StringBuilder innerUrlBuilder = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            if (i == ids.size() - 1) {
                innerUrlBuilder.append(id);
            } else {
                innerUrlBuilder.append(id).append(",");
            }
        }
        String url = String.join("=", innerUrl, innerUrlBuilder.toString());
        //设置请求头信息



        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WiW64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<HttpHeaders> entity = new HttpEntity<>(headers);
        //发起请求
//        String result = restTemplate.postForObject(innerUrl, new HttpEntity<>(headers), String.class);
//        String result = restTemplate.getForObject(innerUrl, String.class);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String result = response.getBody();
        String reg="var hq_str_(.+)=\"(.+)\";";
        Pattern pattern = Pattern.compile(reg);

        Matcher matcher = pattern.matcher(result);
        //收集大盘封装后后的对象
        ArrayList<StockMarketIndexInfo> list = new ArrayList<>();
        while (matcher.find()) {
            //获取大盘的id
            String marketCode = matcher.group(1);
            System.out.println(marketCode);
            //其它信息
            String other = matcher.group(2);
            String[] others = other.split(",");
            //大盘名称
            String marketName=others[0];
            //当前点
            BigDecimal curPoint=new BigDecimal(others[1]);
            //当前价格
            BigDecimal curPrice=new BigDecimal(others[2]);
            //涨跌率
            BigDecimal upDownRate=new BigDecimal(others[3]);
            //成交量
            Long tradeAmount=Long.valueOf(others[4]);
            //成交金额
            Long tradeVol=Long.valueOf(others[5]);
            //当前日期
//            Date now =  DateTimeUtil.getDateTimeWithoutSecond(DateTime.now()).toDate();
            //封装对象
            StockMarketIndexInfo stockMarketIndexInfo = StockMarketIndexInfo.builder().id(idWorker.nextId()+"")
                    .markName(marketName)
                    .tradeVolume(tradeVol)
                    .tradeAccount(tradeAmount)
                    .updownRate(upDownRate)
                    .curTime(LocalDateTime.now())
                    .curPoint(curPoint)
                    .currentPrice(curPrice)
                    .markId(marketCode)
                    .build();
            list.add(stockMarketIndexInfo);
        };
//        log.info("集合长度：{}，内容：{}",list.size(),list);
//        //批量插入
//        if (CollectionUtils.isEmpty(list)) {
//            log.info("");
//            return;
//        }
//        String curTime = DateTime.now().toString(DateTimeFormat.forPattern("yyyyMMddHHmmss"));
//        log.info("采集的大盘数据：{},当前时间：{}",list,curTime);
        //TODO 后续完成批量插入功能
        marketIndexInfoMapper.insertBatch(list);
    }
}
